﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using IToursDataService.Models;

namespace ChinaDynastyTours.Views
{
    public partial class FlightOrderForm : DevExpress.XtraEditors.XtraForm
    {
        public string _FlightCode { get; set; }         //航班号
        public string _StartCity { get; set; }          //始发城市
        public string _EndCity { get; set; }            //到达城市
        public string _StartTime { get; set; }          //始发时间
        public string _EndTime { get; set; }            //结束时间

        DomesticAirline _flightTime = new DomesticAirline(WcfClient.UseService((IToursDataService.ISysParameterCtrl s) => (s.GetValueForKey("FlightTimeServiceURL"))));//SysParameterCtrl.GetValueForKey("FlightTimeServiceURL"));

        List<FlightEntity> _flights = new List<FlightEntity>();
        string _beginCity, _endCity;//用于在线查询时保存起始和终止地址
        public FlightOrderForm()
        {
            InitializeComponent();
        }

        #region 窗口初始化

        private void FlightOrderForm_Load(object sender, EventArgs e)
        {
            tbBeginCity.EditValue = _StartCity.Trim();
            tbEndCity.EditValue = _EndCity.Trim();
            tbBeginCity1.EditValue = _StartCity;
            tbEndCity1.EditValue = _EndCity;

            _flightTime.getDomesticAirlinesTimeCompleted += new getDomesticAirlinesTimeCompletedEventHandler(DomesticAirlinesTimeCompleted);

            //Load bas_Flight data
            btnRefresh.PerformClick();

        }

        void DomesticAirlinesTimeCompleted(object sender, getDomesticAirlinesTimeCompletedEventArgs e)
        {
            DevExpress.Utils.ToolTipController tip = ApplicationHelper.ShowLoadTip("从互联网加载数据...", flightGridControl1);

            try
            {
                if (e.Error != null)
                {
                    MessageBox.Show("查询错误：" + e.Error, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (e.Result.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("查无数据", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                _flights.Clear();
                foreach (DataRow dr in e.Result.Tables[0].Rows)
                    _flights.Add(new FlightEntity { FlightCode = dr["AirlineCode"].ToString(), BeginCity = _beginCity, EndCity = _endCity, BeginPosition = dr["StartDrome"].ToString(), EndPosition = dr["ArriveDrome"].ToString(), StartTime = dr["StartTime"].ToString(), EndTime = dr["ArriveTime"].ToString(), PlaneModel = dr["Mode"].ToString() });

                flightGridControl1.DataSource = _flights;
                flightGridView1.RefreshData();
            }
            finally
            {
                tip.HideHint();
                ProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                ProgressBarEdit.Stopped = true;
                lblProgress.Caption = "完毕";
                btnRefresh1.Enabled = true;
            }
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (sender.Equals(btnRefresh))
            {
                if (tbBeginCity.Text.Trim() == "" && tbEndCity.Text.Trim() == "") return;

                string beginCityPy = CN2PYHelper.CapitalCovert(tbBeginCity.Text);
                string endCityPy = CN2PYHelper.CapitalCovert(tbEndCity.Text);

                flightGridControl.DataSource = WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.GetFlightData(beginCityPy, endCityPy))); //BaseInfoCtrl.GetFlightData(beginCityPy, endCityPy);
            }
            else
            {
                if (tbBeginCity1.Text == "" || tbEndCity1.Text == "")
                {
                    MessageBox.Show("‘出发站’和‘到达站’必须填写！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return;
                }
                //保存变量
                _beginCity = tbBeginCity1.Text;
                _endCity = tbEndCity1.Text;

                btnRefresh1.Enabled = false;
                btnRefresh1.Enabled = false;
                ProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                ProgressBarEdit.Stopped = false;
                lblProgress.Caption = "正在检索...";
                
                string date = tbDateEnable.Checked ? "" : tbDate.DateTime.ToString("yyyy-MM-dd");
                _flightTime.getDomesticAirlinesTimeAsync(tbBeginCity1.Text, tbEndCity1.Text, date, "");
            }
        }

        #endregion

        #region GridView双击行处理
        private void flightGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks == 2)//双击
                if (sender.Equals(flightGridView))
                    btnOK.PerformClick();
                else
                    btnOK1.PerformClick();
           
        } 
        #endregion

        #region '确定'按钮保存数据

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (sender.Equals(btnOK))
            {
                if (flightGridView.FocusedRowHandle < 0) return;

                _FlightCode = flightGridView.GetDataRow(flightGridView.FocusedRowHandle)["FlightCode"].ToString();
                _StartCity = flightGridView.GetDataRow(flightGridView.FocusedRowHandle)["BeginCity"].ToString();
                _EndCity = flightGridView.GetDataRow(flightGridView.FocusedRowHandle)["EndCity"].ToString();
                _StartTime = flightGridView.GetDataRow(flightGridView.FocusedRowHandle)["StartTime"].ToString();
                _EndTime = flightGridView.GetDataRow(flightGridView.FocusedRowHandle)["EndTime"].ToString();
            }
            else
            {
                if (flightGridView1.FocusedRowHandle < 0) return;

                _FlightCode = flightGridView1.GetRowCellValue(flightGridView1.FocusedRowHandle, "FlightCode").ToString();
                _StartCity = flightGridView1.GetRowCellValue(flightGridView1.FocusedRowHandle, "BeginPosition").ToString();
                _EndCity = flightGridView1.GetRowCellValue(flightGridView1.FocusedRowHandle, "EndPosition").ToString();
                _StartTime = flightGridView1.GetRowCellValue(flightGridView1.FocusedRowHandle, "StartTime").ToString();
                _EndTime = flightGridView1.GetRowCellValue(flightGridView1.FocusedRowHandle, "EndTime").ToString();
            }
        }
        #endregion

        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            btnRefresh.PerformClick();
        }
        private void tbDateEnable_CheckedChanged(object sender, EventArgs e)
        {
            tbDate.Enabled = !tbDateEnable.Checked;
        }

        private void btnSaveDB_Click(object sender, EventArgs e)
        {
            if (flightGridView1.FocusedRowHandle < 0) return;

            string tipMsg = string.Format("检索的全部信息将以始发地为‘{0}’和到达地为‘{1}’存储到本地数据库，确定吗？",_beginCity,_endCity);
            if (DialogResult.Yes == MessageBox.Show(tipMsg, "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                DataTable dt = WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.GetFlightData(CN2PYHelper.CapitalCovert(_beginCity), CN2PYHelper.CapitalCovert(_endCity)))); //BaseInfoCtrl.GetFlightData(CN2PYHelper.CapitalCovert(_beginCity), CN2PYHelper.CapitalCovert(_endCity));
                if (dt.Rows.Count > 0)//存在已有相似数据，删除...,再更新
                    foreach (DataRow dr in dt.Rows)
                        WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.DeleteFlightData(dr["FlightID"].ToString()))); //BaseInfoCtrl.DeleteFlightData(dr["FlightID"].ToString());
                //将查到的数据全部存储到数据库
                for (int i = 0; i < _flights.Count; i++)
                {
                    WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.CreateFlightData(_flights[i]))); //BaseInfoCtrl.CreateFlightData(_flights[i]);
                    if (i == _flights.Count - 1)
                        MessageBox.Show("完成存储！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

        }
    }
}
